<?php

!defined('IN_ROOT') && exit('Access Denied');

class areamodel {

    var $db;
    var $base;

    function areamodel(&$base) {
        $this->base = $base;
        $this->db = $base->db;
    }


    /*获取分类信息*/
    function get($id) {
        return $this->db->fetch_first("SELECT * FROM ".DB_TABLEPRE."area WHERE id='$id'");
    }
    function getname_byid($id) {
        $db = $this->db->fetch_first("SELECT name,ename FROM ".DB_TABLEPRE."area WHERE id='$id'");
        if(empty($db['ename'])){
            return $db['name'];
        }else{
            return $db['ename'];
        }
    }
    function get_list() {
        $arealist = array();
        $query = $this->db->query("SELECT * FROM ".DB_TABLEPRE."area");
        while($cate = $this->db->fetch_array($query)) {
            $arealist[] = $cate;
        }
        return $arealist;
    }
    /**
     * 获得分类树
     *
     * @param array $allarea
     * @return string
     */
    function get_categrory_tree($allarea) {
        $categrorytree='';
        $total=count($allarea);
        for($i=0;$i<$total;$i++) {
            if($allarea[$i]['pid']==0) {
                $categrorytree .= "<option value=\"{$allarea[$i]['id']}\">{$allarea[$i]['name']}</option>";
                $categrorytree .=$this->get_child_tree($allarea,$allarea[$i]['id'],1);
            }
        }
        return $categrorytree;
    }
    function get_child_tree($allarea,$pid,$depth=1) {
        $childtree='';
        foreach($allarea as $area) {
            if($pid==$area['pid']) {
                $childtree .= "<option value=\"{$area['id']}\">";
                $depthstr=str_repeat("--", $depth);
                $childtree .= $depth ? "&nbsp;&nbsp;|{$depthstr}&nbsp;{$area['name']}</option>" :"{$area['name']}</option>";
                $childtree .= $this->get_child_tree($allarea, $area['id'],$depth+1);
            }
        }
        return $childtree;
    }

    /*获取某一根节点的所有分类*/
    function list_by_pid($pid,$limit=100) {
        $arealist = array();
        $query = $this->db->query("SELECT * FROM `".DB_TABLEPRE."area` WHERE `pid`=$pid ORDER BY displayorder ASC,id ASC LIMIT $limit");
        while($area = $this->db->fetch_array($query)) {
            $arealist[] = $area;
        }
        return $arealist;
    }

    /*分类浏览页面显示子分类*/
    function list_by_cid_pid($cid,$pid) {
        $sublist=array();
        $query=$this->db->query("select id,name,grade from ".DB_TABLEPRE."area where pid=$cid order by displayorder asc,id asc");
        $subcount=$this->db->affected_rows();
        if($subcount<=0) {
            $query=$this->db->query("select id,name,grade from ".DB_TABLEPRE."area where pid=$pid order by displayorder asc,id asc");
        }
        while($area=$this->db->fetch_array($query)) {
            $sublist[]=$area;
        }
        return $sublist;
    }

    /*用于提问时候分类的选择*/
    function get_js($cid = 0) {
        (!$cid) && $cid=$cid;
        $areajs=$area1=$area2=$area3='';
        $query=$this->db->query("SELECT *  FROM ".DB_TABLEPRE."area WHERE `id` != $cid order by displayorder asc ");
        while($area=$this->db->fetch_array($query)) {
            switch($area['grade']) {
            	case 0:
                    $area0.='["'.$area['id'].'","'.$area['name'].'"],';
                    break;
                case 1:
                    $area1.='["'.$area['pid'].'","'.$area['id'].'","'.$area['name'].'"],';
                    break;
                case 2:
                    $area2.='["'.$area['pid'].'","'.$area['id'].'","'.$area['name'].'"],';
                    break;
                case 3:
                    $area3.='["'.$area['pid'].'","'.$area['id'].'","'.$area['name'].'"],';
                    break;
            }
        }
        $area0=substr($area0,0,-1);
        $area1=substr($area1,0,-1);
        $area2=substr($area2,0,-1);
        $area3=substr($area3,0,-1);
        $areajs="{\"area0\":[$area0],\"area1\":[$area1],\"area2\":[$area2],\"area3\":[$area3]}";
        return $areajs;
    }

    /*分类显示页面分类导航*/
    function get_navigation($cid=0,$contain=false) {
        $navlist=array();
        do {
            $area=$this->base->area[$cid];
            if($area) {
                $cid=$area['pid'];
                $navlist[]=$area;
            }
        }while($area && $cid);
        $navlist=array_reverse($navlist);
        !$contain && array_pop($navlist); //是否需要本分类
        return $navlist;
    }

    /*后台管理批量添加分类*/
    function add($lines,$pid=0,$displayorder=0,$questions=0) {
        $grade = (0==$pid)? 1: $this->base->area[$pid]['grade'] + 1;
        $sql = "INSERT INTO `".DB_TABLEPRE."area`(`pid` ,`dir` ,  `grade` , `name` ,`pinyin` ,`displayorder`) VALUES ";
        
        foreach($lines as $line) {
            $line=str_replace(array("\r\n", "\n", "\r"), '', $line);
            if(empty($line))continue;
            @list($name,$areadir)=explode('，' , $line);
            $areadir=empty($areadir)?getpinyin($name):$areadir;
            $pinyin = strtoupper(substr($areadir,0,1));
            $sql .= "($pid,'$areadir', $grade,'$name','$pinyin',$displayorder),";
            $displayorder++;
        }
        $sql=substr($sql,0,-1);
        //var_dump($sql);exit();
        return $this->db->query($sql);
    }

    /*后台管理编辑分类*/
    function update_by_id($id,$name,$areadir,$pid) {
        $grade = (0==$pid)? 1: $this->base->area[$pid]['grade'] + 1;
        $this->db->query("UPDATE `".DB_TABLEPRE."area` SET  `pid`=$pid ,`grade`=$grade , `name`='$name', `dir`='$areadir' WHERE `id`=$id");
    }

    /*后台管理删除分类*/
    function remove($cids) {
        $this->db->query("DELETE FROM `".DB_TABLEPRE."area` WHERE `id` IN  ($cids)");
    }

    /*后台管理移动分类顺序*/
    function order_area($id,$order) {
        $this->db->query("UPDATE `".DB_TABLEPRE."area` SET 	`displayorder` = '{$order}' WHERE `id` = '{$id}'");
    }
    function area_option($pid,$selectId='')
	{	
		$cate_cache_array = $this->base->area;
		static $i = 0;
		
		foreach ($cate_cache_array as $v)	
		{
			if($v['pid'] == $pid)
			{
				if($selectId == $v['id'])
					$select = 'selected';
				else 
					$select = '';
					
				echo '<option value="' . $v['id'] . '" ' . $select . '>' . str_repeat('--|', $i) . $v['name'] . '</option>';
				$i++;
				
				if($this->has_sub($v['id']))
				{
					$this->area_option($v['id'],$selectId);
				}
				
				$i--;
			}
		}
	}
	function has_sub($id)
	{
		$cate_cache_array = $this->base->area;
		
		$flag = false;
		
		foreach ($cate_cache_array as $v)
		{
			if($v['pid']==$id)
				$flag = true;
		}
		return $flag;
	}
	function select_option_cate($selectId = '')
	{
		ob_start();
		$tree_view_str = '<select name="pid">';
		$tree_view_str .= '<option value="0">选择分类</option>';
			
		$this->area_option('0',$selectId);
			
		$tree_view_str .= ob_get_contents();
			
		ob_end_clean();
			
		$tree_view_str .= '</select>';
		return $tree_view_str;
	}

}
?>
